package com.poisonh.unifiedauth.ui;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.baidu.ocr.sdk.OCR;
import com.baidu.ocr.sdk.OnResultListener;
import com.baidu.ocr.sdk.exception.OCRError;
import com.baidu.ocr.sdk.model.AccessToken;
import com.baidu.ocr.sdk.model.IDCardParams;
import com.baidu.ocr.sdk.model.IDCardResult;
import com.lzy.okhttputils.model.HttpParams;
import com.poisonh.unifiedauth.R;
import com.poisonh.unifiedauth.model.IdCard;
import com.poisonh.unifiedauth.ui.ocr.camera.OcrCameraActivity;
import com.poisonh.unifiedauth.ui.svprogresshud.SVProgressHUD;
import com.poisonh.unifiedauth.utils.ConstantUitls;
import com.poisonh.unifiedauth.utils.FileUtil;
import com.poisonh.unifiedauth.utils.MyHttpsUtils;
import com.poisonh.unifiedauth.utils.Photoutils;
import com.poisonh.unifiedauth.utils.RegexUtils;
import com.poisonh.unifiedauth.utils.ToastUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import io.realm.Realm;

/**
 * 绑定用户身份证信息
 * Created by PoisonH on 2016/6/28.
 */
public class IdCardSettingActivity extends BaseActivity implements View.OnClickListener
{
    private static final int PERMISSIONS_WRITEEXTERNAL_STORAGE = 803;
    //姓名输入框
    private EditText mName;
    //身份证输入框
    private EditText mIdNumber;
    private EditText mGender;
    private EditText mNation;
    private EditText mBrith;
    private EditText mAddress;
    //绑定身份按钮
    private Button mBtnSave;
    //用户姓名
    private String mStrName;
    //身份证号
    private String mStrNumber;
    //姓名至少2位
    private boolean name2bit = false;
    //身份证至少17位
    private boolean card18bit = false;

    private boolean haveHeadImg = false;

    private final int TAKEPHOTO_CODE=2;
    public static final String action="idcard.scan";

    private String  imagePath;

    private ImageView mMyHead;

    private static final int REQUEST_CODE_CAMERA = 102;
    private AlertDialog.Builder alertDialog;

    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE};

    @Override
    protected void loadContentView(Bundle savedInstanceState)
    {
        setContentView(R.layout.activity_id_card_setting);
        initTitleView();
        initView();
        initAccessTokenWithAkSk();

        verifyStoragePermissions(IdCardSettingActivity.this);

    }

    @Override
    protected void initView()
    {
        mRightBtn.setVisibility(View.GONE);
        mLeftBtn.setOnClickListener(this);
        mName = (EditText) findViewById(R.id.et_name);
        mIdNumber = (EditText) findViewById(R.id.et_id_number);
        mGender = (EditText) findViewById(R.id.et_gender);
        mNation = (EditText) findViewById(R.id.et_nation);
        mAddress = (EditText) findViewById(R.id.et_address);
        mBrith = (EditText) findViewById(R.id.et_birth);
        mMyHead = (ImageView) findViewById(R.id.id_head);
        mName.addTextChangedListener(mNameTextWatcher);
        mIdNumber.addTextChangedListener(mCardTextWatcher);
        mBtnSave = (Button) findViewById(R.id.btn_save_id_card);
        mBtnSave.setOnClickListener(this);
        setTitleTxt("身份证");
    }

    @Override
    public void onClick(View v)
    {
        switch (v.getId())
        {
            case R.id.ib_left_btn:
                finish();
                break;
            case R.id.btn_save_id_card://下一步的点击事件
                mStrName = mName.getText().toString();
                mStrNumber = mIdNumber.getText().toString();
                if (!RegexUtils.isIdCard(mStrNumber))
                {
                    ToastUtils.showToast(IdCardSettingActivity.this, "请输入正确的身份证号码");
                } else
                {
                    saveCardInfo();
                }
                break;
        }
    }

    public void verifyStoragePermissions(Activity activity) {
        // Check if we have write permission
        int permission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (permission != PackageManager.PERMISSION_GRANTED) {
            // We don't have permission so prompt the user
            ToastUtils.showToast(IdCardSettingActivity.this, "年轮认证需要读写手机存储权限！请再权限管理中选择允许");
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                ActivityCompat.requestPermissions(this,
                        new String[] {Manifest.permission.READ_EXTERNAL_STORAGE},
                        PERMISSIONS_WRITEEXTERNAL_STORAGE);
            }
            finish();
        }else{
            //百度OCR身份证识别
        Intent intent = new Intent(IdCardSettingActivity.this, OcrCameraActivity.class);
        intent.putExtra(OcrCameraActivity.KEY_OUTPUT_FILE_PATH,FileUtil.getSaveFile(getApplication()).getAbsolutePath());
        intent.putExtra(OcrCameraActivity.KEY_CONTENT_TYPE, OcrCameraActivity.CONTENT_TYPE_ID_CARD_FRONT);//15676795164
        startActivityForResult(intent, REQUEST_CODE_CAMERA);
        }
    }

    private void recIDCard(final String idCardSide, final String filePath) {
        IDCardParams param = new IDCardParams();
        param.setImageFile(new File(filePath));
        param.setIdCardSide(idCardSide);
        param.setDetectDirection(true);
        OCR.getInstance().recognizeIDCard(param, new OnResultListener<IDCardResult>() {
            @Override
            public void onResult(IDCardResult result) {
                if (result != null) {
                    try {
                        mName.setText(result.getName().toString());
                        mGender.setText(result.getGender().toString());
                        mNation.setText(result.getEthnic().toString());
                        String brithDay = result.getBirthday().toString().substring(0, 4) + "年" + result.getBirthday().toString().substring(4, 6) + "月" + result.getBirthday().toString().substring(6, 8) + "日";
                        mBrith.setText(brithDay);
                        mAddress.setText(result.getAddress().toString());
                        mIdNumber.setText(result.getIdNumber().toString());
                        name2bit = true;
                        card18bit = true;
                        changeBtnState();
                    }catch (Exception e)
                    {
                        e.printStackTrace();
                        ToastUtils.showToast(IdCardSettingActivity.this, "获取身份证信息失败！");
                        SVProgressHUD.dismiss(IdCardSettingActivity.this);
                    }
                }
            }

            @Override
            public void onError(OCRError error) {
                recIDCard(idCardSide,filePath);
 //               SVProgressHUD.dismiss(IdCardSettingActivity.this);
            }
        });
    }

    @Override
    protected void onActivityResult(int arg0, int arg1, Intent data) {
//        super.onActivityResult(arg0, arg1, data);
        if(data==null){
            finish();
            return;
        }
        Uri uri = data.getData();
        if (arg0 == REQUEST_CODE_CAMERA && arg1 == Activity.RESULT_OK) {
            SVProgressHUD.showWithStatus(this, "加载中...");
            if (data != null) {
                String contentType = data.getStringExtra(OcrCameraActivity.KEY_CONTENT_TYPE);
                String filePath = FileUtil.getSaveFile(getApplicationContext()).getAbsolutePath();
                cutHeadImg(filePath);
                if (!TextUtils.isEmpty(contentType)) {
                    if (OcrCameraActivity.CONTENT_TYPE_ID_CARD_FRONT.equals(contentType)) {
                        recIDCard(IDCardParams.ID_CARD_SIDE_FRONT, filePath);
                    } else if (OcrCameraActivity.CONTENT_TYPE_ID_CARD_BACK.equals(contentType)) {
                        recIDCard(IDCardParams.ID_CARD_SIDE_BACK, filePath);
                    }
                }
            }
        }else{
            finish();
        }
//        if(arg1== Activity.RESULT_OK){
//            switch (arg0) {
//                case TAKEPHOTO_CODE:
//                    String result = data.getStringExtra("result");
//                    Log.d(tag, "result:  "+result);
//                    try {
//                        JSONObject mjson = new JSONObject(result);
//                        if(mjson.getString("status").equals("OK")){
//                            JSONObject mjson2 = mjson.getJSONObject("data");
//                            JSONObject mjson3 = mjson2.getJSONObject("item");
//                            mName.setText(mjson3.getString("name"));
//                            mGender.setText(mjson3.getString("sex"));
//                            mNation.setText(mjson3.getString("folk"));
//                            mBrith.setText(mjson3.getString("birthday"));
//                            mAddress.setText(mjson3.getString("address"));
//                            mIdNumber.setText(mjson3.getString("cardno"));
//                            Bitmap bitmap = convertStringToIcon(mjson3.getString("header_pic"));
//                            mMyHead.setImageBitmap(bitmap);
//                            imagePath = Photoutils.savePhoto(bitmap, Environment.getExternalStorageDirectory().getAbsolutePath(), "idhead");
//                            name2bit = true;
//                            card18bit = true;
//                            changeBtnState();
//                        }
//                    } catch (JSONException e)
//                    {
//                        e.printStackTrace();
//                    }
//                    break;
//            }
//        }
    }

    private void initAccessTokenWithAkSk() {
        OCR.getInstance().initAccessTokenWithAkSk(new OnResultListener<AccessToken>() {
            @Override
            public void onResult(AccessToken result) {
                String token = result.getAccessToken();
            }

            @Override
            public void onError(OCRError error) {
                error.printStackTrace();
                ToastUtils.showToast(IdCardSettingActivity.this, "AK，SK方式获取token失败");
            }
        }, getApplicationContext(), "R10Pb1ZEBp352G41M8naVZ6y", "dpQwP45PhoxB3BAPoGjwhXbN3voh0SNM");
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[]  permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            initAccessTokenWithAkSk();
        } else {
            Toast.makeText(getApplicationContext(), "需要手机读取存储权限,请到应用设置中开启,否则将无法正常使用!", Toast.LENGTH_LONG).show();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 释放内存资源
        OCR.getInstance().release();
    }

    /**
     * string转成bitmap
     *
     * @param st
     */
    public static Bitmap convertStringToIcon(String st)
    {
//        OutputStream out;
        Bitmap bitmap = null;
        try
        {
//            out = new FileOutputStream("/sdcard/aa.jpg");
            byte[] bitmapArray;
            bitmapArray = Base64.decode(st, Base64.DEFAULT);
            bitmap =
                    BitmapFactory.decodeByteArray(bitmapArray, 0,
                            bitmapArray.length);

//            bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
            return bitmap;
        }
        catch (Exception e)
        {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 保存信息
     */
    private void saveCardInfo()
    {
        HttpParams params = new HttpParams();
        params.put("userId", mStrUserId);
        params.put("token", mStrUserToken);
        params.put("name", mStrName);
        params.put("idNumber", mStrNumber);

        params.put("sex",mGender.getText().toString());
        params.put("familyName",mNation.getText().toString());
        String brith =  mBrith.getText().toString();

        try {
            Date date = new SimpleDateFormat("yyyy年MM月dd日").parse(brith);
            String d = new SimpleDateFormat("yyyy-MM-dd").format(date);
            params.put("birth",d);
        } catch (ParseException e) {
            e.printStackTrace();
        }


        params.put("address",mAddress.getText().toString());

        params.put("headImgFile",new File(imagePath));

        MyHttpsUtils.post(ConstantUitls.REQUEDT_URL + ConstantUitls.SAVEIDSETTING, params, new MyHttpsUtils.ResultCallback()
        {
            @Override
            public void onSuccess(String response)
            {
                ToastUtils.showToast(IdCardSettingActivity.this, "更新身份证成功");
                Intent mIntent = new Intent();
                JSONObject resultsJson = null;
                Realm realm = null;
                try {
                    JSONObject  responseJson  = new JSONObject(response);
                    resultsJson = responseJson.getJSONObject("results");
                    realm =  Realm.getDefaultInstance();
                    realm.beginTransaction();
                    realm.createOrUpdateObjectFromJson(IdCard.class,resultsJson);
                    realm.commitTransaction();
                    mIntent.putExtra("result","seccuss");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                finally {
                    if (realm!=null){
                        realm.close();
                    }
                }
                setResult(IdentityCardActivity.TYPE_IDCARD, mIntent);
                finish();
                Intent intent_card=new Intent(IdCardSettingActivity.this,CameraActivity.class);
                startActivity(intent_card);

            }

            @Override
            public void onFailure(String failReason)
            {
                Log.e("身份更新状态",failReason);
                ToastUtils.showToast(IdCardSettingActivity.this, failReason);
            }
        });
    }

    /**
     * 剪切头像
     */
    private void cutHeadImg(final String headImgPath)
    {
        HttpParams params = new HttpParams();
        params.put("userId", mStrUserId);
        params.put("token", mStrUserToken);
        params.put("headImgFile",new File(headImgPath));

        MyHttpsUtils.post(ConstantUitls.REQUEDT_URL + ConstantUitls.HEADLOCATION, params, new MyHttpsUtils.ResultCallback()
        {
            @Override
            public void onSuccess(String response)
            {
//                ToastUtils.showToast(IdCardSettingActivity.this, response);
                try {
                    JSONObject mjson = new JSONObject(response);
                    if (mjson.getString("code").equals("200")) {
                        JSONObject mjson2 = mjson.getJSONObject("results");
                        JSONArray mjson3 = mjson2.getJSONArray("result");
                        JSONObject mjson4 = mjson3.getJSONObject(0);
                        JSONObject mjson5 = mjson4.getJSONObject("location");
                        int rotation_angle = mjson4.getInt("rotation_angle");
                        int x = mjson5.getInt("left");
                        int y = mjson5.getInt("top");
                        int width = mjson5.getInt("width");
                        int height = mjson5.getInt("height");

                        Bitmap bitmap = BitmapFactory.decodeFile(headImgPath);
                        Bitmap cutHead = Bitmap.createBitmap(bitmap, x-100, y-120, width+200, height+240);
                        mMyHead.setImageBitmap(cutHead);
                        imagePath = Photoutils.savePhoto(cutHead, Environment.getExternalStorageDirectory().getAbsolutePath(), "idhead");
                        haveHeadImg = true;
                        changeBtnState();
                    }
                } catch (JSONException e)
                   {
                        e.printStackTrace();
                       ToastUtils.showToast(IdCardSettingActivity.this, "获取用户头像失败,请重试");
                       Intent intent = new Intent(IdCardSettingActivity.this, OcrCameraActivity.class);
                       intent.putExtra(OcrCameraActivity.KEY_OUTPUT_FILE_PATH,
                               FileUtil.getSaveFile(getApplication()).getAbsolutePath());
                       intent.putExtra(OcrCameraActivity.KEY_CONTENT_TYPE, OcrCameraActivity.CONTENT_TYPE_ID_CARD_FRONT);
                       startActivityForResult(intent, REQUEST_CODE_CAMERA);
                       SVProgressHUD.dismiss(IdCardSettingActivity.this);
                   }
            }

            @Override
            public void onFailure(String failReason)
            {
                ToastUtils.showToast(IdCardSettingActivity.this, "获取用户头像失败,请重试");
                Intent intent = new Intent(IdCardSettingActivity.this, OcrCameraActivity.class);
                intent.putExtra(OcrCameraActivity.KEY_OUTPUT_FILE_PATH,
                        FileUtil.getSaveFile(getApplication()).getAbsolutePath());
                intent.putExtra(OcrCameraActivity.KEY_CONTENT_TYPE, OcrCameraActivity.CONTENT_TYPE_ID_CARD_FRONT);
                startActivityForResult(intent, REQUEST_CODE_CAMERA);
                SVProgressHUD.dismiss(IdCardSettingActivity.this);
            }
        });
    }

    //编辑框监听器
    TextWatcher mNameTextWatcher = new TextWatcher()
    {
        private CharSequence temp;

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after)
        {
            temp = s;
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count)
        {

        }

        @Override
        public void afterTextChanged(Editable s)
        {
            if (temp.length() >= 2)
            {
                name2bit = true;
                changeBtnState();
            } else
            {
                name2bit = false;
                changeBtnState();
            }
        }
    };
    TextWatcher mCardTextWatcher = new TextWatcher()
    {
        private CharSequence temp;

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after)
        {
            temp = s;
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count)
        {

        }

        @Override
        public void afterTextChanged(Editable s)
        {
            if (temp.length() == 18)
            {
                card18bit = true;
                changeBtnState();
            } else
            {
                card18bit = false;
                changeBtnState();
            }
        }
    };

    /**
     * 根据输入动态改变按钮状态
     */
    private void changeBtnState()
    {
        if (name2bit && card18bit && haveHeadImg)
        {
            SVProgressHUD.dismiss(IdCardSettingActivity.this);
            mBtnSave.setEnabled(true);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                mBtnSave.setBackground(getResources().getDrawable(R.drawable.shape_settingmyinfo_btn_bg));
            }
        } else
        {
            mBtnSave.setEnabled(false);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN
                    ) {
                mBtnSave.setBackground(getResources().getDrawable(R.drawable.shape_settingmyinfo_btn_bg_));
            }
        }
    }
}
